﻿Option Explicit On
Option Strict On

' Espacios de nombres
' '''''''''''''''''''''''''''''''''''''''''
Imports System.Data.SqlClient

Public Class EditProfile
    Dim query As String = "SELECT     * from perfiles order by nombre"

    'BindingSource
    Private WithEvents bs As New BindingSource

    ' Adaptador de datos sql
    Private SqlDataAdapter As SqlDataAdapter

    ' Cadena de conexión
    Private Const cs As String = "Data Source=143.116.204.27;Initial Catalog=Emulator;Persist Security Info=True;User ID=gerardo_martinez;Password=Sanmina01"

    ' flag
    Private bEdit As Boolean


    ' actualizar los cambios al salir
    ' ''''''''''''''''''''''''''''''''''''''''
    Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        If bEdit Then
            'preguntar si se desea guardar
            If (MsgBox("Save changes?", MsgBoxStyle.YesNo, "Save")) = MsgBoxResult.Yes Then
                Actualizar(False)
            End If
        End If
    End Sub

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        ' propiedades del datagrid
        ' '''''''''''''''''''''''''''''''''''''
        With DataGridView1
            ' alternar color de filas
            .AlternatingRowsDefaultCellStyle.BackColor = Color.FloralWhite
            .DefaultCellStyle.BackColor = Color.Beige
            ' Establecer el origen de datos para el DataGridview
            .DataSource = bs
        End With
        ' botones
        ' '''''''''''''''''''''''''''''''''''''
        'btn_Update.Text = "Guardar cambios"
        'btn_delete.Text = "Eliminar registro"
        'btn_new.Text = "Nuevo"
        ' cagar los datos
        cargar_registros(query, DataGridView1)
    End Sub

    Private Sub cargar_registros(ByVal sql As String, ByVal dv As DataGridView)

        Try
            ' Inicializar el SqlDataAdapter indicandole el comando y el connection string
            SqlDataAdapter = New SqlDataAdapter(sql, cs)

            Dim SqlCommandBuilder As New SqlCommandBuilder(SqlDataAdapter)

            ' llenar el DataTable
            Dim dt As New DataTable()
            SqlDataAdapter.Fill(dt)

            ' Enlazar el BindingSource con el datatable anterior
            ' ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
            bs.DataSource = dt

            With dv
                .Refresh()
                ' coloca el registro arriba de todo
                .FirstDisplayedScrollingRowIndex = bs.Position
            End With

            bEdit = False

        Catch exSql As SqlException
            MsgBox(exSql.Message.ToString)
        Catch ex As Exception
            MsgBox(ex.Message.ToString)
        End Try
        DataGridView1.Columns(0).Visible = False
    End Sub

    ' botón para guardar los cambios y llenar la grilla
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_update.Click
        Actualizar()
    End Sub

    Private Sub btn_exit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_exit.Click
        Me.Close()
    End Sub

    ' Eliminar el elemento actual del BindingSource y actualizar
    Private Sub btn_delete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_delete.Click
        If Not bs.Current Is Nothing Then
            If MsgBox("If you delete this profile, all the units assigned to it will be deleted too, Are you sure?", MsgBoxStyle.OkCancel, "Alert!") = MsgBoxResult.Ok Then
                ' eliminar
                bs.RemoveCurrent()
                Config.lblselectedprofile.Text = ""
                For i As Integer = 0 To Config.DataGridView1.RowCount - 1
                    Config.DataGridView1.Rows.Remove(Config.DataGridView1.CurrentRow)
                Next
                'Config.DataGridView1.DataSource =Config.
                'Guardar los cambios y recargar
                Config.cbxprofiles.Items.Clear()
                Config.cbxprofiles.Text = ""
                Actualizar()
            End If
        Else
            MsgBox("There is no current record to delete!", MsgBoxStyle.Information, "No record selected!")
        End If

    End Sub

    Public Sub Actualizar(Optional ByVal bCargar As Boolean = True)
        ' Actualizar y guardar cambios
        If Not bs.DataSource Is Nothing Then
            SqlDataAdapter.Update(CType(bs.DataSource, DataTable))
            If bCargar Then
                cargar_registros(query, DataGridView1)
            End If
            Config.LoadAll()
        End If
    End Sub

    Private Sub DataGridView1_CellEndEdit(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellEndEdit
        bEdit = True
    End Sub

    Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        AddProfile.ShowDialog()
    End Sub
End Class